<template>
    <el-container>
      <el-header>
        <el-row justify="space-between" align="middle">
          <el-col :span="24">
            <h3 style="color: gray;text-align:center">用户个人中心</h3>
          </el-col>
        </el-row>
      </el-header>
  
      <el-main>
        <el-card>
          <el-form :model="userData" label-width="120px" class="user-form">
            <el-form-item label="手机号（账号）">
              <el-input v-model="userData.adminPhone" disabled></el-input>
            </el-form-item>
  
            <el-form-item label="上次登录时间">
              <el-input v-model="userData.lastLogtime" disabled></el-input>
            </el-form-item>
  
            <el-form-item label="权限等级">
              <el-input v-model="userData.authorityLevel" disabled></el-input>
            </el-form-item>
  
            <!-- 修改手机号表单显示控制 -->
            <el-form-item v-if="showPhoneForm">
              <el-input v-model="newPhoneData.phone" placeholder="请输入新的手机号"></el-input>
              <el-button type="primary" @click="updatePhone">确认修改</el-button>
              <el-button @click="showPhoneForm = false">取消</el-button>
            </el-form-item>
            <el-form-item v-else>
              <el-button type="primary" @click="showPhoneForm = true">修改手机号</el-button>
            </el-form-item>
  
            <!-- 修改密码表单显示控制 -->
            <el-form-item v-if="showPasswordForm">
              <el-input v-model="newPasswordData.password" type="password" placeholder="请输入新的密码"></el-input>
              <el-input v-model="newPasswordData.confirmPassword" type="password" placeholder="请再次输入密码"></el-input>
              <el-button type="primary" @click="updatePassword">确认修改</el-button>
              <el-button @click="showPasswordForm = false">取消</el-button>
            </el-form-item>
            <el-form-item v-else>
              <el-button type="primary" @click="showPasswordForm = true">修改密码</el-button>
            </el-form-item>
  
           
          </el-form>
        </el-card>
      </el-main>
    </el-container>
  </template>
  
  
<script setup>
import axios from 'axios';
import { ref, onMounted } from 'vue';

    const userData = ref({
      adminPhone: '',
      lastLogtime: '',
      authorityLevel: '',
    });

    const newPhoneData = ref({ phone: '' });
    const newPasswordData = ref({
      password: '',
      confirmPassword: '',
    });

    const showPhoneForm = ref(false);
    const showPasswordForm = ref(false);
    const updateMessage = ref('');

    const fetchUserData = async () => {
      const adminId = localStorage.getItem('adminId');
      console.log('adminId:', adminId);

      if (!adminId) {
        ElMessage.error('未找到当前登录用户');
        return;
      }

      try {
        const response = await axios.get('/getUserInfo', {
          params: { adminId },
        });

        console.log(response.data);

        if (response.data.success) {
          userData.value = response.data.userData;
          console.log('Updated userData:', userData.value);
        } else {
          ElMessage.error('获取用户信息失败');
        }
      } catch (error) {
        ElMessage.error('请求失败，请重试');
        console.error('Error fetching data:', error);
      }
    };

    const updatePhone = async () => {
      try {
        const adminId = localStorage.getItem('adminId');

        if (!adminId) {
          ElMessage.error('管理员 ID 未找到');
          return;
        }

        const response = await axios.put(
          'http://localhost:8088/administrators/updatePhone',
          {
            adminId,
            newPhone: newPhoneData.value.phone,
          },
          {
            headers: {
              'Content-Type': 'application/json',
            },
          }
        );

        handleResponseMessage(response.data.message);
        showPhoneForm.value = false;
        await fetchUserData();
      } catch (error) {
        ElMessage.error('请求失败，请重试');
        console.error(error);
      }
    };

    const updatePassword = async () => {
      if (newPasswordData.value.password !== newPasswordData.value.confirmPassword) {
        ElMessage.error('两次密码输入不一致');
        return;
      }

      if (newPasswordData.value.password.length < 6) {
        ElMessage.error('密码长度必须大于6位');
        return;
      }

      try {
        const adminId = localStorage.getItem('adminId');
        if (!adminId) {
          ElMessage.error('管理员 ID 未找到');
          return;
        }

        const response = await axios.put(
          'http://localhost:8088/administrators/updatePassword',
          {
            adminId,
            newPassword: newPasswordData.value.password,
          },
          {
            headers: {
              'Content-Type': 'application/json',
            },
          }
        );

        handleResponseMessage(response.data.message);
        showPasswordForm.value = false;
      } catch (error) {
        ElMessage.error('请求失败，请重试');
        console.error(error);
      }
    };

    const handleResponseMessage = (message) => {
      switch (message) {
        case 'success':
          updateMessage.value = '更新成功';
          ElMessage.success({
            message: '更新成功',
            duration: 1500,
          });
          break;
        case 'invalidPhone':
          updateMessage.value = '手机号格式不正确';
          ElMessage.error({
            message: '手机号格式不正确',
            duration: 1500,
          });
          break;
        case 'adminNotFound':
          updateMessage.value = '管理员不存在';
          ElMessage.error({
            message: '管理员不存在',
            duration: 1500,
          });
          break;
        case 'phoneExists':
          updateMessage.value = '该手机号已被注册';
          ElMessage.error({
            message: '该手机号已被注册',
            duration: 1500,
          });
          break;
        case 'error':
          updateMessage.value = '操作失败，请稍后重试';
          ElMessage.error({
            message: '操作失败，请稍后重试',
            duration: 1500,
          });
          break;
        default:
          updateMessage.value = '未知错误';
          ElMessage.warning({
            message: '未知错误',
            duration: 1500,
          });
          break;
      }
    };

    onMounted(() => {
      fetchUserData();
    });

</script>
  
  
<style scoped>
  .el-card {
    width: 100%;
    max-width: 400px;
    margin: 20px auto;
  }
  
  .user-form {
    width: 100%;
    max-width: 360px;
    margin: 20px auto;
  }
  
  .el-form-item {
    margin-bottom: 24px; /* 增大输入框之间的间距 */
  }
  
  .el-button {
    margin-top: 10px; /* 增大按钮与输入框之间的间距 */
  }
  
  .el-card {
    padding: 20px;
  }
  
  @media (max-width: 768px) {
    .el-card {
      width: 100%;
      max-width: 100%;
    }
  
    .user-form {
      max-width: 100%;
    }
  }
  </style>
  
  
  